<template>
    <div class="login-container">
        <el-form ref="loginForm" :model="loginForm" :rules="loginRules" label-position="top">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="loginForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input type="password" v-model="loginForm.password"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="login">登录</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import { login as loginApi} from '@/api/login-api';

export default {
    name: 'Login',
    data() {
        return {
            loginForm: {
                username: '',
                password: ''
            },
            loginRules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' }
                ]
            }
        };
    },
    methods: {
        async login() {
            this.$refs.loginForm.validate(async valid => {
                if (valid) {
                    try {
                        const response = await loginApi(this.loginForm.username, this.loginForm.password);
                        // 记录返回的 token 到 localStorage
                        localStorage.setItem('token', response.token);
                        console.log('登录成功');
                        // 登录成功后跳转到首页
                        this.$router.push('/');
                    } catch (error) {
                        console.error('登录失败:', error);
                        // 可以在这里添加错误提示，比如使用 Element UI 的消息提示组件
                        this.$message.error('登录失败，请检查用户名和密码');
                    }
                } else {
                    console.log('表单验证失败');
                }
            });
        }
    }
};
</script>

<style scoped>
.login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}
</style>